//
//  MujiDubVCTableViewCell.m
//  testdemo
//
//  Created by yule on 2017/5/17.
//  Copyright © 2017年 yule. All rights reserved.
//

#import "MujiDubVCTableViewCell.h"
#import "MujiDubDialogLinesModel.h"
#import <AVFoundation/AVFoundation.h>
#import "MujiDubFilePathUtility.h"

#import "MujiDubRecorder.h"
#import "MujiDubHeader.h"
#import "MujiDubViewController.h"
#import "MBProgressHUD.h"
#import "MujiDubTextHeightTool.h"
#import "MujiDubWordModel.h"
#import <lame/lame.h>
#import "MujiDubDatabaseManager.h"
#import "MujiDubTools.h"
#import "MujiDubRecordModel.h"
#import "MujiDubButton.h"

#define MujiDubSINGLE_LINE_HEIGHT           (1 / [UIScreen mainScreen].scale)
#define MujiDubSINGLE_LINE_WIDTH           (1 / [UIScreen mainScreen].scale)



@interface MujiDubVCTableViewCell()<MujiDubRecorderDelegate, AVAudioPlayerDelegate>
@property (nonatomic, strong) UIView *wordView;


@property (nonatomic,assign) int                   curFontSize;
@property (nonatomic,assign) int                   curTransFontSize;

@property (nonatomic, strong) UIButton *slowPlayBtn;
@property (nonatomic, strong) UIView   *backView;
@property (nonatomic, strong) UIView   *separatorLine;

@property (nonatomic, strong) UIImageView   *playRecordImageView;
@property (nonatomic, strong) UIImageView   *recordImageView;
@property (nonatomic, strong) UIView   *btnContainView;
//@property (nonatomic, strong) UIButton *playRecordBtn;
@property (nonatomic, strong) UIButton   *recordBtn;
@property (nonatomic, strong) UIButton   *playBtn;
@property (nonatomic, strong) UILabel *labelScore;
@property (nonatomic, strong) UILabel *labelPage;
@property (nonatomic, strong) UIImageView *imageViewScore;
@property (nonatomic, strong) UILabel *durationLabel;


@property (nonatomic, strong) MujiDubDialogLinesModel   *curModel;
//@property (nonatomic, strong) NSString   *curDialogId;
@property (nonatomic, strong) NSMutableArray  *curWordArray;

@property (nonatomic, assign) BOOL isSelected;

@property (nonatomic, strong) NSDate *recordDate;
@property (nonatomic, strong) AVAudioPlayer *avAudioPlayer;
@property (nonatomic, assign) BOOL isHaveResult;
@property (nonatomic, assign) BOOL isSessionEnd;
@property (readwrite, nonatomic, strong)  MujiDubRecorder *dialogLineRecorder;
//@property (readwrite, nonatomic, strong) ECSpeechDialogLineAnalysisResult *dialogLineAnalysisResult;

@property (nonatomic, strong, readwrite) NSTimer *slowSpeakAudioTimer;
@property (nonatomic, strong, readwrite) NSData *slowAudioData;
@property (nonatomic, assign, readwrite) double slowSpeakStart;
@property (nonatomic, assign, readwrite) double slowSpeakEnd;
@property (nonatomic, assign) BOOL   isCancel;

@property (nonatomic, copy) NSString   *lineScore;

@property (nonatomic, assign) BOOL   recordIsplaying;

@property (nonatomic, assign) BOOL   playingRecordIsPause;


@property (nonatomic, strong)  dispatch_source_t timer;
@property (nonatomic, strong)  NSDate  *timerBegintime;

@property (nonatomic, strong)  UITapGestureRecognizer  *playRecordGesture;

@property (nonatomic, strong) MujiDubButton   *lastSelectBtn;


@end


@implementation MujiDubVCTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    
    // Configure the view for the selected state
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.backView = [[UIView alloc] initWithFrame:CGRectMake(24, 10, self.frame.size.width - 12 - 12, self.frame.size.height - 10)];
        
        [self addSubview:self.backView];
        
        self.backView.backgroundColor = [UIColor whiteColor];
        
        
        self.labelScore = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width - 30, 10, 25, 30)];
        
        self.labelScore.textColor = [UIColor whiteColor];
        self.labelScore.textAlignment = NSTextAlignmentCenter;
        self.labelScore.font = [UIFont systemFontOfSize:14];
        
        self.userInteractionEnabled = YES;
        
        self.imageViewScore = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width - 40, 8, 40, 24)];
        
        [self addSubview:self.imageViewScore];
        [self addSubview:self.labelScore];
        
        self.separatorLine = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height - MujiDubSINGLE_LINE_HEIGHT, self.frame.size.width, MujiDubSINGLE_LINE_HEIGHT)];
        self.separatorLine.backgroundColor = ColorWithRGBA(212, 212, 212, 1.0);
        [self addSubview:self.separatorLine];

        
        _curFontSize = 20;
        _curTransFontSize = 13;
        if(kIS_IPHONE_6)
        {
            _curFontSize = 20;
            _curTransFontSize = 13;
        }
        
        [self initRecordUI];
    }
    
    return self;
}


-(void)initRecordUI
{
    self.isCancel = NO;
    self.recordIsplaying = NO;
    
    int high_ContainView = 48;
    int btn_width = 32;
    /* 录音功能按钮 容器  */
    self.btnContainView  = [[ UIView alloc] initWithFrame:CGRectMake((kScreenWidth - 284) / 2, kScreenHeight-10, 284, high_ContainView)];
    self.btnContainView.userInteractionEnabled = YES;
    self.btnContainView.hidden = YES;
    [self addSubview:self.btnContainView];
    
    int Y_btn = 6;

    /* 播放  */
    _playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _playBtn.frame = CGRectMake(self.btnContainView.frame.size.width - 22 - btn_width, Y_btn, btn_width , btn_width);
    //[_playBtn setImage:[UIImage imageNamed:@"ico_play"] forState:UIControlStateNormal];
    
    //    [_playBtn setImage:[UIImage imageNamed:@"ico_play@3x"] forState:UIControlStateNormal];
    //
    //    [_playBtn setImage:[UIImage imageNamed:@"icon_player_disable"] forState:UIControlStateDisabled];
    
    [_playBtn setBackgroundImage:[UIImage imageNamed:@"icon_player"] forState:UIControlStateNormal];
    [_playBtn setBackgroundImage:[UIImage imageNamed:@"icon_player_disable"] forState:UIControlStateDisabled];
    
    //_playBtn.backgroundColor = [UIColor redColor];
    
    [_playBtn addTarget:self action:@selector(playVideo) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_playBtn];
    _playBtn.enabled = NO;
    
    /* 录音  */
    _recordBtn= [UIButton buttonWithType:UIButtonTypeCustom];
    _recordBtn.frame = CGRectMake( (self.btnContainView.frame.size.width - btn_width - 22 - CGRectGetMinX(_playBtn.frame)), Y_btn, btn_width , btn_width);
    
   // _recordBtn.backgroundColor = [UIColor redColor];
    //[_recordBtn setBackgroundImage:[UIImage imageNamed:@"ico_play@3x"] forState:UIControlStateNormal];
    
    [_recordBtn addTarget:self action:@selector(onBtnRecord) forControlEvents:UIControlEventTouchUpInside];
    _recordBtn.enabled = YES;
    
    
    _recordImageView =  [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth- btn_width)/2 , Y_btn, btn_width , btn_width)];
    _recordImageView.image = [UIImage imageNamed:@"icon_record_disable"];
    NSMutableArray * animateArray1 = [[NSMutableArray alloc]initWithCapacity:6];
    //_playRecordImaneView = [[UIImageView alloc] initWithFrame:CGRectMake(60+10+148+15, 0, 60, 60)];
   // _recordImageView.backgroundColor = [UIColor redColor];
     _recordImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTapRecord =  [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playRecordBtnDidClicked:)];
    [_recordImageView addGestureRecognizer:singleTapRecord];
    //    [_recordImageView addGestureRecognizer:singleTapRecord];
    
    
    _playRecordBtn= [UIButton buttonWithType:UIButtonTypeCustom];
    _playRecordBtn.frame = _playRecordImageView.frame;
    _playRecordBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [_playRecordBtn addTarget:self action:@selector(playRecordBtnDidClicked) forControlEvents:UIControlEventTouchUpInside];
    
    /* 页码显示  */
    self.labelPage = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - 12 - 12 - 35 - 20, 10, 35, 20)];
    self.labelPage.textColor = ColorWithRGBA(255, 255, 255, 1.0);
    self.labelPage.textAlignment = NSTextAlignmentCenter;
    self.labelPage.font = [UIFont systemFontOfSize:10];
    
    self.durationLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - 12 - 12 - 35 - 20, 10, 35, 20)];
    self.durationLabel.textColor = ColorWithRGBA(154, 154, 154, 1.0);
    self.durationLabel.textAlignment = NSTextAlignmentRight;
    self.durationLabel.font = [UIFont systemFontOfSize:11];
    self.durationLabel.hidden = YES;
    
    //[self.btnContainView addSubview:self.playBtn];
    //[self.btnContainView addSubview:self.playRecordImageView];
    //[self.btnContainView addSubview:self.recordImageView];
    //[self.btnContainView addSubview:self.slowPlayBtn];
    [self.btnContainView addSubview:self.playRecordBtn];
    [self.btnContainView addSubview:self.recordBtn];
    [self.btnContainView addSubview:self.durationLabel];

    [self addSubview:self.labelPage];

    
}
- (void)setRecordResultStatus:(BOOL)status
{
    if (status) {
        self.isHaveResult = YES;
    }else {
        self.isHaveResult = NO;
        
    }
}

- (void)setRecordResultImageViewStatus:(BOOL)status
{
    if (status) {
        
        [self.playRecordImageView startAnimating];
        
        
    }else {
        [self.playRecordImageView stopAnimating];
        _playRecordImageView.image = [UIImage imageNamed:@"icon_playrecord"];
        
    }
}

-(void)resetBtnStatus:(BOOL)btnStatus  playRecordStatus:(BOOL)status
{
    if (status) {
        
        if(self.isHaveResult)
        {
            [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord"] forState:UIControlStateNormal];
            [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_Highlighted"] forState:UIControlStateHighlighted];

            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record"] forState:UIControlStateNormal];
            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_Highlighted"] forState:UIControlStateHighlighted];

        }
        else
        {
            self.recordImageView.image = [UIImage imageNamed:@""];
            [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        }
    }else {
    }
}


- (void)refreshData:(MujiDubDialogLinesModel *)model words:(NSMutableArray *)wordArray selected:(BOOL)bSelect anyResult:(id)resultModel
{
    // NSLog(@"%@", model);
    self.isSelected = bSelect;
    
    self.btnContainView.frame  = CGRectMake(0, self.frame.size.height - 48, self.frame.size.width, 48);
    //self.btnContainView.backgroundColor = [UIColor blueColor];
    
    //self.btnContainView.hidden = !bSelect;
    
    self.btnContainView.hidden = NO;
    
    self.labelScore.frame = CGRectMake(self.frame.size.width - 25, 10, 25, 30);
    
    self.imageViewScore.frame = CGRectMake(self.frame.size.width - 34, 10, 34, 30);
    
    [self.backView setFrame:CGRectMake(12, 10, self.frame.size.width - 12 - 12, self.frame.size.height - 10)];
    
    //self.labelPage.backgroundColor = [UIColor blueColor];
    
    [self.wordView removeFromSuperview];
    
    self.wordView = [[UIView alloc] initWithFrame:CGRectMake(12, 30, self.frame.size.width - 12 - 12, self.frame.size.height - 100)];
    
    [self addSubview:self.wordView];
    [self.labelPage setFrame:CGRectMake(self.frame.size.width - 35 - 20 - 12, 10, 35, 21)];
    self.labelPage.text = [NSString stringWithFormat:@"%d/%d", self.index + 1, self.totalIndex];
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.labelPage.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(2, 2)];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc]init];
    //设置大小
    maskLayer.frame = self.labelPage.bounds;
    //设置图形样子
    maskLayer.path = maskPath.CGPath;
    self.labelPage.layer.mask = maskLayer;
    
    if(bSelect)
    {
        //self.backgroundColor = [UIColor whiteColor];
        //self.labelPage.text =  [self.parentVC getPages];
        
        // CGFloat width = [MujiDubTextHeightTool getStringWidthWithString:[self.parentVC getPages] height:MAXFLOAT font:11];
        // [self.labelPage setFrame:CGRectMake(self.frame.size.width - 12 - 12 - 40 - 11, 10, 40, 21)];
        
        self.wordView.userInteractionEnabled = YES;
        self.btnContainView.userInteractionEnabled = YES;
             _recordImageView.userInteractionEnabled = YES;
        
        //[_recordBtn setImage:[UIImage imageNamed:@"icon_dub_record@2x"] forState:UIControlStateNormal];
        // _recordBtn.backgroundColor = [UIColor redColor];
        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record"] forState:UIControlStateNormal];
        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_Highlighted"] forState:UIControlStateHighlighted];

        self.labelPage.backgroundColor = ColorWithRGBA(255, 195, 0, 1.0);
    }
    else
    {
        self.backgroundColor = ColorWithRGBA(235, 235, 235, 1.0);
        self.wordView.userInteractionEnabled = NO;
        self.btnContainView.userInteractionEnabled = NO;

        self.labelPage.backgroundColor = ColorWithRGBA(214, 214, 214, 1.0);
        
       // self.playRecordBtn.enabled = NO;
        //self.recordBtn.enabled = NO;
        //[_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_disable"] forState:UIControlStateNormal];
    }
    
    self.curModel = model;
    self.curWordArray = wordArray;
    
    NSMutableArray *letters = [[NSMutableArray alloc] init];
    NSMutableString *transcript = [NSMutableString stringWithString:model.transcript];
    NSMutableString *lowTranscipt = [NSMutableString stringWithString:[transcript lowercaseString]];
    
    NSString *curTail = @"";
    
    //获取单词
    
    for (int j = 0; j < [wordArray count]; j++)
    {
        NSRange range = [lowTranscipt rangeOfString:[NSString stringWithFormat:@"%@",[((MujiDubWordModel *)wordArray[j]).orthography lowercaseString]]];
        
        //        if(j == [wordArray count] - 1)
        //        {
        //            if(range.location + range.length < lowTranscipt.length)
        //            {
        //                curTail = [transcript substringFromIndex:range.location + range.length];
        //
        //            }
        //
        //        }
        
        if (range.location != NSNotFound) {
            
            NSString *word = [transcript substringToIndex:range.location+[((MujiDubWordModel *)wordArray[j]).orthography lowercaseString].length];
            word = [word stringByReplacingOccurrencesOfString:@" " withString:@""];

            //[letters addObject:word];

            [letters addObject:[transcript substringToIndex:range.location+[((MujiDubWordModel *)wordArray[j]).orthography lowercaseString].length]];
            transcript = [NSMutableString stringWithString:[transcript substringFromIndex:range.location+[((MujiDubWordModel *)wordArray[j]).orthography lowercaseString].length]];
            lowTranscipt = [NSMutableString stringWithString:[lowTranscipt substringFromIndex:range.location+[((MujiDubWordModel *)wordArray[j]).orthography lowercaseString].length]];
        }
    }
    
    CGFloat myHeight = 10;
    if(kIS_IPHONE_6)
    {
        myHeight = 20;
    }
    
    CGFloat totalWidth = 20;
    int lines = 0;
    CGFloat lastY = 0;
    
    CGFloat height_single = [MujiDubTextHeightTool getHeightWithString:@"faffafaf" width:self.wordView.frame.size.width font:_curFontSize].height;
    
    for (int j = 0; j < letters.count; j++) {
        
//        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        btn.backgroundColor = [UIColor clearColor];
//        btn.tag = 2345 + j;
//        btn.titleLabel.font = [UIFont systemFontOfSize:_curFontSize];
//        btn.titleLabel.numberOfLines = 0;
//        btn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
//        [btn setTitle:letters[j] forState:UIControlStateNormal];
        MujiDubButton *btn =  [MujiDubButton buttonWithFrame:CGRectMake(0, 0, 30, 30) title:letters[j] image:nil];
        btn.userInteractionEnabled = YES;
        btn.textFont = [UIFont systemFontOfSize:_curFontSize];
        btn.tag =  2345 + j;
        
        if(bSelect)
        {
            [btn setTextColor:[UIColor blackColor]];
        }
        else
        {
            [btn setTextColor:ColorWithRGBA(0, 0, 0, 0.5)];
        }
        
        [btn addTarget:self action:@selector(selectLetterAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.wordView addSubview:btn];
        
        CGFloat width = [MujiDubTextHeightTool getHeightWithString:letters[j] width:self.wordView.frame.size.width font:_curFontSize].width;
        CGFloat height = [MujiDubTextHeightTool getHeightWithString:letters[j] width:self.wordView.frame.size.width font:_curFontSize].height;
        
        if(height > height_single)
        {
            height += 10;
        }
        
        btn.frame = CGRectMake(totalWidth, height_single * lines + 5 * (lines + 1), width, height);
        totalWidth += width;
        
        if (totalWidth > self.wordView.frame.size.width - 20*2) {
            lines++;
            totalWidth = 20;
            btn.frame = CGRectMake(totalWidth, height_single * lines + 5 * (lines + 1), width, height);
            totalWidth += width;
        }
        
        if(j == letters.count - 1)
        {
            //lastY = CGRectGetMaxY(btn.frame);
            if(![curTail isEqualToString:@""])
            {
                CGFloat tail_width = [MujiDubTextHeightTool getHeightWithString:curTail width:self.wordView.frame.size.width font:_curFontSize].width;
                
                CGFloat tail_height = [MujiDubTextHeightTool getHeightWithString:curTail width:self.wordView.frame.size.width font:_curFontSize].height;
                
                UILabel *tailLbl = [[UILabel alloc] initWithFrame:CGRectMake(totalWidth, height_single * lines + 5 * (lines + 1), tail_width, tail_height)];
                tailLbl.text =  curTail;
                tailLbl.font = [UIFont systemFontOfSize:_curFontSize];
                totalWidth += tail_width;
                
                if (totalWidth > self.wordView.frame.size.width-20*2) {
                    lines++;
                    totalWidth = 20;
                    tailLbl.frame = CGRectMake(totalWidth, height_single * lines + 5 * (lines + 1), tail_width, tail_height);
                    totalWidth += width;
                }
                [self.wordView addSubview:tailLbl];
                
                lastY = CGRectGetMaxY(tailLbl.frame);
            }
            else
            {
                lastY = CGRectGetMaxY(btn.frame);
            }
            
        }
    }
    
   // _btnContainView.backgroundColor = [UIColor redColor];
    
    //NSLog(@"  --------- %f", lastY);
    //model.translation = @"呵呵额呵呵呵呵呵额呵呵呵呵呵额呵呵呵呵呵额呵呵呵呵呵额呵呵呵呵呵额呵呵呵";
    if(model.translation.length > 0 && self.parentVC.isShowChinese)
    {
        UILabel *meansLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, lastY + 16, (self.frame.size.width - 12 - 12 - 20 - 20), [MujiDubTextHeightTool getHeightWithString:model.translation width:self.wordView.frame.size.width font:_curTransFontSize].height +5 )];
        meansLbl.font = [UIFont systemFontOfSize:_curTransFontSize];
        
        if(bSelect)
        {
            meansLbl.textColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.65];
        }
        else
        {
            meansLbl.textColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.35];
        }
        
        meansLbl.numberOfLines = 0;
        meansLbl.text = model.translation;
        [self.wordView addSubview:meansLbl];
        
       // meansLbl.backgroundColor = [UIColor orangeColor];
        
        lastY = CGRectGetMaxY(meansLbl.frame);
    }
    
    self.wordView.frame =  CGRectMake(12, 30, self.frame.size.width - 12 - 12, lastY);
    
    //self.wordView.backgroundColor = [UIColor blueColor];
    
    self.labelScore.text = @"";
    
    [self.separatorLine setFrame:CGRectMake(12 + 20,  self.frame.size.height - 48, (self.frame.size.width - 12 - 12 - 20 - 20), MujiDubSINGLE_LINE_HEIGHT)];
    
    [self.btnContainView setFrame:CGRectMake(12 + 20, self.frame.size.height - 48, self.frame.size.width - 12 - 12 - 20 - 20, 48)];
    //[self.playBtn ]
    //_playBtn.frame = CGRectMake(self.btnContainView.frame.size.width - 22 - 32, 6, 32 , 32);
    _recordBtn.frame = CGRectMake(self.btnContainView.frame.size.width - 32, 6, 32 , 32);
    
    _recordImageView.frame = CGRectMake( (self.btnContainView.frame.size.width - (32 + 32 + 22) - 50), 6, 32 , 32);
    
    
    if (self.playRecordGesture) {
        [_recordBtn removeGestureRecognizer:self.playRecordGesture];
        
//        self.playRecordGesture =  [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(playRecordBtnDidClicked:)];
//        [_recordImageView addGestureRecognizer:singleTapRecord];

    }
    
    _playRecordBtn.frame = CGRectMake( (self.btnContainView.frame.size.width - (32 + 32 + 22)), 6, 32 , 32);
    
    _durationLabel.frame = CGRectMake((self.btnContainView.frame.size.width - (32 + 32 + 22) - 20 - 100), (48 - 12)/2, 100, 12);
    
    if(resultModel != nil){
        // [self showResultInLetter:resultModel.resultAnalysis];
        //self.labelScore.text = resultModel.score;
        // [self showScoreBackground:resultModel.score];
        self.imageViewScore.hidden = NO;
        self.labelScore.hidden = NO;
        self.isHaveResult = YES;
        
        self.playRecordBtn.hidden = NO;
        
//        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record"] forState:UIControlStateNormal];
//        [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_Highlighted"] forState:UIControlStateHighlighted];
        if (bSelect) {
            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record"] forState:UIControlStateNormal];
            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_Highlighted"] forState:UIControlStateHighlighted];

            self.recordImageView.image = [UIImage imageNamed:@"icon_dub_playrecord"];
            
            [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord"] forState:UIControlStateNormal];
            [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_Highlighted"] forState:UIControlStateHighlighted];

            
        }else {
            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_disable"] forState:UIControlStateNormal];
            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_disable"] forState:UIControlStateHighlighted];

            
            self.recordImageView.image = [UIImage imageNamed:@"icon_dub_playrecord"];
            
            [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_disable"] forState:UIControlStateNormal];
            [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_disable"] forState:UIControlStateHighlighted];

            
        }
        
        NSLog(@"正在播放录音中  4333333333333333333333333 --> 暂停");


        self.labelPage.backgroundColor = ColorWithRGBA(255, 195, 0, 1.0);
        
    }
    else
    {
        self.labelScore.hidden = YES;
        self.imageViewScore.hidden = YES;
        self.isHaveResult = NO;
        
        self.playRecordBtn.hidden = YES;
        if (!bSelect) {
            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_disable"] forState:UIControlStateNormal];
            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_disable"] forState:UIControlStateHighlighted];

        }
    }
}

- (void)setWordBackGroundColorWithIndex:(int)index status:(int)status
{
//    UIButton *btn = [self viewWithTag:2345+index];
//    
//    if (status == 0) {
//        btn.backgroundColor = [UIColor clearColor];
//    }else {
//        //[btn setBackgroundColor:ColorWithRGBA(255, 195, 0, 1.0)];
//        
//        btn.titleLabel.backgroundColor = ColorWithRGBA(255, 195, 0, 1.0);
//        
//            if (self.lastSelectBtn && self.lastSelectBtn.tag != btn.tag) {
//            [self.lastSelectBtn setBackgroundColor:[UIColor clearColor]];
//        }
//    }
//    self.lastSelectBtn = btn;
    
    
    
    MujiDubButton *btn = [self viewWithTag:2345+index];
    
    if (status == 0) {
       // btn.backgroundColor = [UIColor clearColor];
        
        [btn setSelectedCloror:[UIColor clearColor]];
        
    }else {
        //[btn setBackgroundColor:ColorWithRGBA(255, 195, 0, 1.0)];
        
       // btn.titleLabel.backgroundColor = ColorWithRGBA(255, 195, 0, 1.0);
        
        [btn setSelectedCloror:ColorWithRGBA(255, 195, 0, 1.0)];

        
        if (self.lastSelectBtn && self.lastSelectBtn.tag != btn.tag) {
            //[self.lastSelectBtn setBackgroundColor:[UIColor clearColor]];
            
            [self.lastSelectBtn setSelectedCloror:[UIColor clearColor]];
        }
    }
    self.lastSelectBtn = btn;

    
}

-(void)playVideo
{
    [self.parentVC playVideo];
    
}

-(void)stopPlayRecord
{
    
    //NSLog(@"%@", )
    
    [self.avAudioPlayer stop];
    
    if (self.avAudioPlayer != nil && [self.avAudioPlayer isPlaying])
    {
        [self.avAudioPlayer stop];
        [self.playRecordImageView stopAnimating];
        _playRecordImageView.image = [UIImage imageNamed:@"icon_playrecord_disable"];
        
    }
}

//设置播放录音状态
- (void)setPlayRecordStatus:(int)status
{
    //status   1 开始播放   2 结束播放  0 暂停播放
    
    if (status == 1) {//  开始播放录音
        
        self.recordIsplaying = YES;
        self.playingRecordIsPause = NO;
        [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_pauseplayrecord"] forState:UIControlStateNormal];
        [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_pauseplayrecord_Highlighted"] forState:UIControlStateHighlighted];
        
    }else if (status == 2){//  结束播放录音
        
        NSLog(@" ---22222222-- ");
        
        self.recordIsplaying = NO;
        self.playingRecordIsPause = NO;
        
        NSLog(@" 当前线程  %@",[NSThread currentThread]);

        if ([NSThread isMainThread])
        {
            
            if (!self.isRecording) {
                self.recordImageView.image = [UIImage imageNamed:@"icon_dub_playrecord"];
                
                [self.recordImageView setNeedsDisplay];
                NSLog(@" ----------- 当前线程  %@",[NSThread currentThread]);
                [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord"] forState:UIControlStateNormal];
                [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_Highlighted"] forState:UIControlStateHighlighted];
                
                [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord"] forState:UIControlStateNormal];
                [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_Highlighted"] forState:UIControlStateHighlighted];
                [self.playRecordBtn setNeedsDisplay];

            }
        }
        else
        {
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                NSLog(@" 111111111 当前线程  %@",[NSThread currentThread]);
                self.recordImageView.image = [UIImage imageNamed:@"icon_dub_playrecord"];


                [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord"] forState:UIControlStateNormal];
                [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_Highlighted"] forState:UIControlStateHighlighted];
                [self.playRecordBtn setNeedsDisplay];
                
            });
        }
    }else if (status == 0){//  播放中到暂停
        
        self.playingRecordIsPause = YES;
        self.recordIsplaying = NO;
    }
}
//播放录音
- (void)playRecordBtnDidClicked
{
    if (self.isRecording) {
        
        return;
        
    }
    
    if (self.recordIsplaying) {//  正在播放录音中  --> 暂停
        [self.parentVC pausePlayRecord];
        
        
        NSLog(@"正在播放录音中  --> 暂停");
        
        [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord"] forState:UIControlStateNormal];
        [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_Highlighted"] forState:UIControlStateHighlighted];
        [self.recordImageView setNeedsDisplay];


    }else {//  开始播放
        
        self.recordImageView.image = [UIImage imageNamed:@"icon_dub_pauseplayrecord"];

        [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_pauseplayrecord"] forState:UIControlStateNormal];
        [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_pauseplayrecord_Highlighted"] forState:UIControlStateHighlighted];
        [self.recordImageView setNeedsDisplay];


        if (self.playingRecordIsPause) {//  暂停到播放
            [self.parentVC playRecordBtnDidClickedWithScore:self.lineScore status:2];

        }else {//  播放结束 到 开始播放
            [self.parentVC playRecordBtnDidClickedWithScore:self.lineScore status:1];

        }
    }
}

- (void)setPlayRecordBtn
{
    [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord"] forState:UIControlStateNormal];
    [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_Highlighted"] forState:UIControlStateHighlighted];
    

}

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    
    [self.playRecordImageView stopAnimating];
    
    _playRecordImageView.image = [UIImage imageNamed:@"icon_playrecord"];
    
    [self resetBtnStatus:YES playRecordStatus:YES];
    
    
    if([self.parentVC showCompleteView] == NO)
    {
        if([self.lineScore intValue] > 70)
        {
            [self.parentVC playNextVideo];
        }
    }
}
- (NSString *)isWAVFileWith
{
    
    NSString *userId = self.userId;
    
    NSString *libaryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *wavPath = [libaryPath stringByAppendingPathComponent:@"UserAudio"];
    
    NSString *secondPath = [wavPath stringByAppendingPathComponent:@"UserWAVCopy"];
    NSString *wavName = [NSString stringWithFormat:@"%@_%@_%@_copy.wav",
                         userId,
                         self.curModel.dialogId,
                         self.curModel.dialogLineID];
    
    NSLog(@"%@", wavName);
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //    NSString *wavName = [NSString stringWithFormat:@"%@_%@_%@.wav", userID, self.curModel.dialogId, self.curModel.dialogLineID];
    NSString *filePath = [secondPath stringByAppendingPathComponent:wavName];
    
    if(![fileManager fileExistsAtPath:filePath]) {//如果不存在
        return @"";
    }else {
        return filePath;
    }
}
/*!
 *  开始录音
 *
 *  @param sender startBtn
 */
- (void)onBtnRecord
{
    //_playRecordBtn.hidden = YES;
    if(!self.isRecording)
    {
        self.isRecording = YES;
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(recordingBegin)]) {
            
            [self.delegate recordingBegin];
            
        }
        
        self.isCancel = NO;
        //开始录音
        MujiDubFilePathUtility *filePathUtility = [MujiDubFilePathUtility sharedUtility];
        NSString *userAudioDirectory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudio];
        
        self.dialogLineID = self.curModel.dialogLineID;
        self.dialogId = self.curModel.dialogId;
        
        
        NSDictionary *dict = @{@"dialogId":self.curModel.dialogId, @"dialogLineID":self.curModel.dialogLineID};
        
        if (self.curModel.dialogId.length != 0 && self.curModel.dialogLineID.length != 0 && self.userId.length != 0) {
            self.dialogLineRecorder = [[MujiDubRecorder alloc] initWithInfo:dict path:userAudioDirectory userId:self.userId];
            self.dialogLineRecorder.delegate = self;
            
            [self.dialogLineRecorder startRecording];
            
            [[self dialogLineRecorder] setDelegate:self];
            self.durationLabel.hidden = NO;
            self.durationLabel.text = [NSString stringWithFormat:@"原句用时%.2fs", [self getDialogDurationWithModel:self.curModel]];
            
            // NSLog(@"%@", userAudioDirectory);
            self.recordDate = [NSDate date];
            // Start recording:
            //[[self dialogLineRecorder] startRecording];
            
            self.isSessionEnd=NO;
            self.playBtn.enabled = NO;
            self.playRecordBtn.enabled = YES;
            self.playRecordBtn.hidden = NO;

            self.recordImageView.image = [UIImage imageNamed:@"icon_dub_recording"];
            
            self.recordBtn.userInteractionEnabled = NO;
            
            [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_recording"] forState:UIControlStateNormal];
            
            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_disable"] forState:UIControlStateNormal];
            [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_disable"] forState:UIControlStateHighlighted];

            //self.recordBtn.hidden = NO;
            [self beginCountdown];
            
            int lineDuring = [self getTimeWithModel:self.curModel];
            int delay;
            if (lineDuring == 0) {
                delay = 5;
            }else {
                delay = lineDuring *3 + 2;
            }
        }else {
            
        }
    }else{//  结束录音
    }
}
- (void)beginCountdown
{
    self.timerBegintime = [[MujiDubTools share] getCurrentTime];

    __block float time = 0; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
     _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0), 0.01*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        
        time += 0.01;
        
        //NSLog(@"%.1f", time);
        float times = [[MujiDubTools share] dateTimeDifferenceWithStartTime:self.timerBegintime];

        if (self.isRecording) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                NSString *title = [NSString stringWithFormat:@"%.2fs", times];
                
                [self.playRecordBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
                [self.playRecordBtn setTitle:title forState:UIControlStateNormal];
            });

            
            float dialogDuration = [self getDialogDurationWithModel:self.curModel];
            
            if (times > dialogDuration) {
                
                self.isRecording = NO;
                
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                               {
                                   [self.dialogLineRecorder stopRecording];
                               });

                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    self.playBtn.enabled = YES;
                    
                    //self.recordBtn.hidden = NO;
                    //  self.playRecordBtn.hidden = NO;
                    _playRecordBtn.enabled = YES;
                    
                    self.recordBtn.userInteractionEnabled = YES;
                    [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record"] forState:UIControlStateNormal];
                    [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_Highlighted"] forState:UIControlStateHighlighted];

                    if (_timer) {
                        dispatch_source_cancel(_timer);
                    }
                    
                    self.durationLabel.hidden = YES;
                    self.durationLabel.text = @"";

                    [self.playRecordBtn setTintColor:[UIColor whiteColor]];
                    [self.playRecordBtn setTitle:@"" forState:UIControlStateNormal];
                    
                    [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord"] forState:UIControlStateNormal];
                    [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_Highlighted"] forState:UIControlStateHighlighted];

                  });
               }
            }
    });
    dispatch_resume(_timer);
    
}

- (void)convertWavToMp3WithFilePath:(NSString *)filePath
{
    if (filePath.length != 0) {
        
        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:filePath]) {
            
            MujiDubFilePathUtility *filePathUtility = [MujiDubFilePathUtility sharedUtility];
            NSString *userAudioMP3Directory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudioMP3];
            NSString *userAudioDirectory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudio];
            
            if ([self checkMP3Directory:userAudioMP3Directory]) {
                userAudioMP3Directory = [userAudioMP3Directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/sectionMP3Data", self.userId, self.dialogId]];

                userAudioDirectory = [userAudioDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/sectionData", self.userId, self.dialogId]];

                NSString *cafFileName = [NSString stringWithFormat:@"%@_%@_%@.wav",
                                         self.userId,
                                         self.dialogId,
                                         self.dialogLineID];
                
                NSString *mp3FileName = [NSString stringWithFormat:@"%@_%@_%@.mp3",
                                         self.userId,
                                         self.dialogId,
                                         self.dialogLineID];
                NSString *cafFilePath = [userAudioDirectory stringByAppendingPathComponent:cafFileName];
                
                NSString *mp3FilePath = [userAudioMP3Directory stringByAppendingPathComponent:mp3FileName];
                
                CGFloat sampleRate  = 44100;
                
                @try {
                    int read, write;
                    
                    
                    FILE *pcm = fopen([cafFilePath cStringUsingEncoding:1], "rb");  //source
                    fseek(pcm, 4*1024, SEEK_CUR);                                   //skip file header
                    FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb");  //output
                    
                    const int PCM_SIZE = 8192;
                    const int MP3_SIZE = 8192;
                    short int pcm_buffer[PCM_SIZE*2];
                    unsigned char mp3_buffer[MP3_SIZE];
                    
                    lame_t lame = lame_init();
                    lame_set_in_samplerate(lame, sampleRate);
                    lame_set_VBR(lame, vbr_default);
                    lame_init_params(lame);
                    
                    do {
                        read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
                        if (read == 0)
                            write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
                        else
                            write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
                        
                        fwrite(mp3_buffer, write, 1, mp3);
                        
                    } while (read != 0);
                    
                    lame_close(lame);
                    fclose(mp3);
                    fclose(pcm);
                }
                @catch (NSException *exception) {
                    NSLog(@"%@",[exception description]);
                }
                @finally {
                    [self performSelectorOnMainThread:@selector(convertMp3Finish)
                                           withObject:nil
                                        waitUntilDone:YES];
                }
            }else {
                
            }
        }
    }else {
        
    }
}
- (BOOL)checkMP3Directory:(NSString *)directory
{
    NSString *path = [directory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@/sectionMP3Data", self.userId, self.dialogId]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *outError = nil;
    
    if ([fileManager fileExistsAtPath:path])
    {
        return YES;
        //[_mutablePaths setObject:userAudio forKey:@(MujiDubFilePathDirectoryUserAudio)];
    }
    else
    {
        if ([fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&outError])
        {
            return YES;
        }else {
            return NO;
        }
    }
}
- (void) convertMp3Finish
{
    
    NSLog(@"转换成功");
    
    MujiDubFilePathUtility *filePathUtility = [MujiDubFilePathUtility sharedUtility];
    NSString *userAudioMP3Directory       = [filePathUtility getPathOfDirectory:MujiDubFilePathDirectoryUserAudioMP3];
    
    NSLog(@"%@", userAudioMP3Directory);
}

- (int)getTimeWithModel:(MujiDubDialogLinesModel *)curmodel
{
    
    // NSLog(@"%@  %@", curmodel.cueEnd, curmodel.cueStart);
    
    int start = [curmodel.cueStart intValue];
    int end = [curmodel.cueEnd intValue];
    
    
    return ((int)(end - start)/100/10);
    
}
- (float)getDialogDurationWithModel:(MujiDubDialogLinesModel *)curmodel
{
    
    // NSLog(@"%@  %@", curmodel.cueEnd, curmodel.cueStart);
    
    int start = [curmodel.cueStart intValue];
    int end = [curmodel.cueEnd intValue];
    
    int duration = end - start;
    
    NSInteger  minit;
    NSInteger  second;
    minit = duration / 60;
    second = duration - 60 * minit;

    //NSString *
    
    return ((float)duration/1000);
    
}

-(void)selectLetterAction:(MujiDubButton *)sender
{
    if(self.isSelected && !self.isRecording && !self.recordIsplaying){
        
        int index = (int)(sender.tag - 2345);
        [self.parentVC showLetterInfoView:index];
        self.slowPlayBtn.enabled = NO;
        
        [self resetBtnStatus:YES playRecordStatus:YES];
        [self setWordBackGroundColorWithIndex:index status:1];
    }
}

- (void)dialogLineRecorder:(MujiDubRecorder *)dialogLineRecorder
                 withState:(MujiDubDialogLineRecordingState)state
                     error:(NSError *)error
{
    /*!
     TODO: GA for MO-2343: GA EVENTS MASTER DOCUMENT is MISSING new spec for this event:
     */
    
    switch (state)
    {
        case MujiDubDialogLineRecordingStateSuccessful:
            [self handleSuccessfulStateWithDialogLineRecorder:dialogLineRecorder];
            break;
            
        case MujiDubDialogLineRecordingStateCancelled:
            //[self handleCancelledStateWithDialogLineRecorder:dialogLineRecorder error:error];
            break;
            
        case MujiDubDialogLineRecordingStateFailed:
            //[self handleFailedStateWithDialogLineRecorder:dialogLineRecorder error:error];
            break;
            
        default:
            // Other states include:
            //   MujiDubDialogLineRecordingStateRecording
            //   MujiDubDialogLineRecordingStatePaused
            break;
    }
}

- (void)handleError:(NSError *)error
{
    if (error)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[error localizedDescription]
                                                        message:[error localizedFailureReason]
                                                       delegate:nil
                                              cancelButtonTitle:@"确认"
                                              otherButtonTitles:nil, nil];
        [alert show];
    }
}

- (void)handleSuccessfulStateWithDialogLineRecorder:(MujiDubRecorder *)dialogLineRecorder
{
    
    NSLog(@"   -------     handleSuccessfulStateWithDialogLineRecorder@");
    
    if(self.isRecording)
    {
        
        [self onBtnRecord];
        return;
    }
    
    if (!self.isCancel) {
       // [self.parentVC showRecordHUDWithMode:MBProgressHUDModeIndeterminate labelText:@"录音处理中..." animated:YES];
    }
    
    NSString *userId = self.userId;
    NSArray *result = [[MujiDubDatabaseManager shareManager] queryAllHistoryModelWithUserId:userId dialogid:self.curModel.dialogId dialoglineid:self.curModel.dialogLineID];
    MujiDubRecordModel *record = [[MujiDubRecordModel alloc] init];
    record.userId = userId;
    record.dialogid = self.curModel.dialogId;
    record.dialoglineid = self.curModel.dialogLineID;
    record.score = @"0";
    record.result = @"0";
    record.mindex = [NSString stringWithFormat:@"%d", self.index+1];
    
    if (self.curModel.dialogLineID.length == 0) {
        record.dialoglineid = [NSString stringWithFormat:@"%d", self.index+1];
        ;
    }
    
    
    
    if (result.count == 0) {
        [[MujiDubDatabaseManager shareManager] insertResultModel:record];
    }else {
        [[MujiDubDatabaseManager shareManager] updateResultModel:record];
    }
    self.isHaveResult = YES;
    self.playRecordBtn.enabled = YES;

    //self.parentVC
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(recordingEndWithData:)]) {
        
        [self.delegate recordingEndWithData:record];
    }

    NSString *filePath = dialogLineRecorder.wavFilePath;
    __weak __typeof(self) weakself= self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                   {
                       //[wSelf.dialogLineRecorder stopRecording];
                       
                       [weakself convertWavToMp3WithFilePath:filePath];
                       
                   });
}



-(void)closeAllPlay
{
    if(self.isRecording)
    {
        self.isRecording = NO;
        [self.dialogLineRecorder cancelRecording];
        
        
        //[self.dialogLineRecorder stopRecording];
    }
    
    // [self stopPlayRecord];
    
    
    // [self.avAudioPlayer stop];
}

- (void)stopRecording
{
    
    if(self.isRecording)
    {
        self.isRecording = NO;
        [self.dialogLineRecorder cancelRecording];
        
        
        //[self.dialogLineRecorder stopRecording];
    }
    
    
    self.playBtn.enabled = YES;
    
    //self.recordBtn.hidden = NO;
    //  self.playRecordBtn.hidden = NO;
    _playRecordBtn.enabled = YES;
    
    self.recordBtn.userInteractionEnabled = YES;
    [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record"] forState:UIControlStateNormal];
    [_recordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_record_Highlighted"] forState:UIControlStateHighlighted];
    
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
    NSLog(@"正在播放录音中 nnnnnnnnnnnnnnnnnnn  --> 暂停");
    
    self.durationLabel.hidden = YES;
    self.durationLabel.text = @"";
    
    [self.playRecordBtn setTintColor:[UIColor whiteColor]];
    [self.playRecordBtn setTitle:@"" forState:UIControlStateNormal];
    
    [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord"] forState:UIControlStateNormal];
    [self.playRecordBtn setBackgroundImage:[UIImage imageNamed:@"icon_dub_playrecord_Highlighted"] forState:UIControlStateHighlighted];
    
    self.recordIsplaying = NO;
    self.playingRecordIsPause = NO;
    
    //    [_slowPlayBtn setBackgroundImage:[UIImage imageNamed:@"slowSpeak_disable"] forState:UIControlStateNormal];
    //    
    //    [_slowPlayBtn setBackgroundImage:[UIImage imageNamed:@"slowSpeak_disable"] forState:UIControlStateDisabled];
    
    //[_slowPlayBtn setBackgroundImage:[UIImage imageNamed:@"slowSpeak_selected"] forState:UIControlStateDisabled];
    
    //  [_slowPlayBtn setBackgroundImage:[UIImage imageNamed:@"slowSpeak_disable"] forState:UIControlStateDisabled];
    
    
    // [self setRecordResultImageViewStatus:NO];
    
    
//    [self.playRecordImageView stopAnimating];
//    _playRecordImageView.image = [UIImage imageNamed:@"icon_playrecord_disable"];
    
    
}



@end
